<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Cookbookstep;

use think\Db;
use think\Exception;
use think\Request;

class Cookbook extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->defaultOrder = 'create_date DESC';
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        // 食材
        $info['ingredients'] = json_decode($info['ingredients'], true);
        // 烹饪步骤
        $info['cookbookStep']  = Cookbookstep::where('cookbook_id', $id)->order('sort ASC')->select();

        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Save Post
     */
    public function savePost(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {

            Db::startTrans();
            try {
                $data = $request->param();
                $ingredientJson = [];
                if(isset($data['ingredient_name']) && $data['ingredient_name']){
                    foreach ($data['ingredient_name'] as $key => $val) {
                        if(!trim($val)){
                            continue;
                        }
                        $ingredientJson[] = [
                            'name' => $val,
                            'num' => $data['ingredient_num'][$key],
                            'unit' => ''
                        ];
                    }
                }
                $data['ingredients'] = json_encode($ingredientJson);

                if ($data['id']) {
                    // Update data
                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                    //$logInfo = $this->admin->name . '更新了一条' . lang($this->model) . '数据。';
                    $afterAction = '_after_update';
                } else {
                    // Insert data
                    //$data['id'] = Helper::getUUID();
                    //$data['create_date'] = date('Y-m-d H:i:s');
                    //$result = $model->save($data);
                    $model->create_date = date('Y-m-d H:i:s');
                    $model->name = $data['name'];
                    $model->img_url = $data['img_url'];
                    $model->introduction = $data['introduction'];
                    $model->ingredients = $data['ingredients'];
                    $result = $model->save();
                    $result && $data['id'] = $model->id;
                    //$logInfo = $this->admin->name . '添加了一条' . lang($this->model) . '数据。';
                    $afterAction = '_after_insert';
                }

                if ($result !== false) {
                    // 保存烹饪步骤
                    Cookbookstep::where('cookbook_id', $data['id'])->delete();
                    if(isset($data['step_img_url']) && $data['step_img_url']){
                        foreach ($data['step_img_url'] as $stepKey => $stepVal) {
                            if(!trim($stepVal)){
                                continue;
                            }
                            $res = Cookbookstep::insert([
                                'cookbook_id' => $data['id'],
                                'img_url' => $stepVal,
                                'content' => $data['content'][$stepKey],
                                'sort' => $stepKey
                            ]);
                            if($res === false){
                                Db::rollback();
                                return $this->error('保存烹饪步骤失败');
                            }
                        }
                    }

                    // Query执行后的操作
                    $model->$afterAction($data);
                    // 写入日志
                    //Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('保存成功！', 'admin/' . strtolower($this->model) . '/index', $data);
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }

        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $request = $this->request;
        $id = $request->param('id');

        $model = model($this->model);
        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        //$result = $model->where('id', $id)->update(['status' => 0]);
        $result = true;
        if ($result !== false) {
            return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
        }
    }

}